package com.example.lenovo.asia5b.my.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.lenovo.asia5b.my.bean.AccountDetBean;
import com.example.lenovo.asia5b.ui.photoview.ImagePagerActivity;
import com.example.lenovo.asia5b.util.DateUtils;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.StringUtil;
import com.wushi.lenovo.asia5b.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.umeng.socialize.utils.DeviceConfig.context;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * Created by lenovo on 2017/8/21.
 */

public class AccountDetailsDetActivity extends BaseActivity  implements ICallBack {
    private AccountDetBean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_details_det);
        initView();
        billData();
    }

    public void initView() {
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.account_details));
        F.id(public_btn_left).clicked(this);
        if (getIntent().hasExtra("id")) {
            bean = (AccountDetBean)getIntent().getSerializableExtra("id");
            F.id(R.id.txt_invoice_no).text(bean.invoice_no);
            F.id(R.id.txt_order_sn).text(bean.order_sn);
            F.id(R.id.txt_rec_id).text(bean.rec_id);
            F.id(R.id.txt_add_time).text(DateUtils.timedate(bean.add_time));
            F.id(R.id.txt_balance).text(bean.balance);
            F.id(R.id.txt_process_type).text(getResources().getString(R.string.lx)+":\t"+ StringUtil.walletType(AccountDetailsDetActivity.this,bean.process_type));

            F.id(R.id.txt_ck).text(getResources().getString(R.string.ck)+"   "+StringUtil.accountDetailsBillType(AccountDetailsDetActivity.this,bean.process_type));
            F.id(R.id.txt_ck).getTextView().getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG  );
//            if (!TextUtils.isEmpty(bean.bill_image)){
                F.id(R.id.txt_ck).visibility(View.VISIBLE);
                F.id(R.id.txt_ck).clicked(this);
                F.id(R.id.txt_bc).visibility(View.GONE);//隐藏保存按钮
                F.id(R.id.txt_bc).clicked(this);
//            }
            String amount = bean.amount;
            if (bean.amount.indexOf("-")!= -1) {
                F.id(R.id.txt_jie_fang).text(getResources().getString(R.string.df));
            } else {
                F.id(R.id.txt_jie_fang).text(getResources().getString(R.string.jf));
            }
            F.id(R.id.txt_amount_tit).text("RM\t"+amount);
            F.id(R.id.txt_jie).text(amount);
            if (bean.process_type.equals("1")) {
                if (bean.is_paid.equals("1")) {
                    F.id(R.id.txt_ck).visibility(View.VISIBLE);
                } else {
                    F.id(R.id.txt_ck).visibility(View.GONE);
                }
            }
            bean.bill_image=  "";
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case R.id.txt_ck:
                if (TextUtils.isEmpty(bean.bill_image)){
                    return;
                }
                intent = new Intent(AccountDetailsDetActivity.this, ImagePagerActivity.class);
                // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
                ArrayList<String> list_imag = new ArrayList<String>();
                list_imag.add(bean.bill_image);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, list_imag);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
                intent.putExtra("bill_image",bean.bill_image);
                startActivity(intent);
                break;
            case R.id.txt_bc:
                U.Toast(AccountDetailsDetActivity.this, getResources().getString(R.string.ksxz) + "...");
                new Thread() {
                    public void run() {
                        try {
                            Bitmap bitmap = loadImageFromUrl(bean.bill_image);
                            String fileName = (new java.text.SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH)).format(new Date()) + Setting.imageFileNameFormatCode;
                            saveFile(bitmap, fileName);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    };
                }.start();
                break;
            default:
                break;
        }
    }

    /**
     * 保存票据
     */
    public void billData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.ORDER_BILL;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"log_id"+bean.id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("log_id",bean.id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }

    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            final String url = json.getString("image");
                            bean.bill_image =url;
                        }
                        else if (state == 1) {
                            U.Toast(context,context.getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(context, context.getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(context, context.getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(context, context.getResources().getString(R.string.qxsb));
                        } else {
                            F.id(R.id.txt_ck).visibility(View.GONE);
                        }
                    } catch (Exception e) {
                    }
                } else {
                    F.id(R.id.txt_ck).visibility(View.GONE);
                }
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 保存图片
     * @param bm
     * @param fileName
     */
    public void saveFile(Bitmap bm, String fileName) {
        try {
            String path = Setting.IMAGE_ROOTPATH;
            File dirFile = new File(path);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //6.0以上使用getExternalFilesDir()获得存储关联目录进行存储，可以省去获得运行时权限
            //现在暂时使用new File来保存图片
            File myCaptureFile = new File(path,fileName);
            //判断文件是否存在
            if(myCaptureFile.exists()){
                myCaptureFile.delete();
            }
            FileOutputStream bos = new FileOutputStream(myCaptureFile);
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
            //把文件插入到系统图库
//            MediaStore.Images.Media.insertImage(context.getContentResolver(), myCaptureFile.getAbsolutePath(), fileName, null);
            handler.sendEmptyMessage(1);
            //保存图片后发送广播通知更新数据库
//            Uri uri = Uri.fromFile(myCaptureFile);
//            AccountDetailsDetActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (Exception e) {
            handler.sendEmptyMessage(0);
        }

    }
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if(msg.what==1){
//                U.Toast(context, "保存图片成功，路径："+ Setting.IMAGE_ROOTPATH);
                U.Toast(AccountDetailsDetActivity.this, getResources().getString(R.string.xzcg)+Setting.IMAGE_ROOTPATH_2+getResources().getString(R.string.wjj));
            }else if(msg.what==0) {
                U.Toast(AccountDetailsDetActivity.this, getResources().getString(R.string.xzsb));
            }
        };
    };

    public Bitmap loadImageFromUrl(String url) throws Exception {
        final DefaultHttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        HttpResponse response = client.execute(getRequest);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            // System.out.println("Request URL failed, error code =" +
            // statusCode);
            Log.e("PicShow", "Request URL failed, error code =" + statusCode);
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.e("PicShow", "HttpEntity is null");
        }
        InputStream is = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            is = entity.getContent();
            byte[] buf = new byte[1024];
            int readBytes = -1;
            while ((readBytes = is.read(buf)) != -1) {
                baos.write(buf, 0, readBytes);
            }
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (is != null) {
                is.close();
            }
        }
        byte[] imageArray = baos.toByteArray();
        return BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length);
    }
}
